from django.db import models
from django.utils.html import format_html
from django.core.exceptions import ValidationError

from account.models import User
from relation.models import Client, Media
from utils.constants import INVOICE_TYPES_CHOICES
from utils.tools import gen_trans_id


class OrderRefund(models.Model):
    """ 开单/退款 """
    # 记录创建该数据的用户
    user_id = models.ForeignKey(User, on_delete=models.SET_NULL, verbose_name='创建者', null=True, related_name='user_id',
                                help_text='<span style="color:red">默认就行，不用修改</span>')
    sn = models.CharField('开单编号', max_length=64, default=gen_trans_id)
    types = models.SmallIntegerField('开单/退款', choices=INVOICE_TYPES_CHOICES, null=False, blank=False)
    created_at = models.DateField('日期')
    sales = models.CharField('销售', max_length=32)
    operation = models.CharField('运营', max_length=32)
    sales_client = models.ForeignKey(Client, verbose_name='客户', on_delete=models.SET_NULL,
                                     related_name='sales_client', null=True,blank=True)
    sales_media = models.ForeignKey(Media, verbose_name='媒体', on_delete=models.SET_NULL,
                                    related_name='sales_media', null=True, blank=True)
    payee = models.CharField('收款人', max_length=64, null=True, blank=True)
    recharge = models.FloatField('账户币', max_length=64,
                                 help_text='<span style="color:red">退款在前面加个负号</span>')
    client_rebate = models.FloatField('给客户返点', max_length=10)
    media_rebate = models.FloatField('媒体返点', max_length=10)
    top_up = models.ImageField('充值截图', upload_to='%Y%m/chongzhi')
    receipt_img = models.ImageField('收款截图', upload_to='%Y%m/shoukuan', null=True, blank=True)
    pay_img = models.ImageField('打款截图', upload_to='%Y%m/dakuan', null=True, blank=True)
    receipt = models.DecimalField('收款', max_digits=32, decimal_places=2, null=True, blank=True,
                                  help_text='<span style="color:red">如不写，保存时会自动根据账户币和返点计算</span>')
    pay = models.DecimalField('打款', max_digits=32, decimal_places=2, null=True, blank=True,
                              help_text='<span style="color:red">如不写，保存时会自动根据账户币和返点计算</span>')
    profit = models.DecimalField('利润', max_digits=32, decimal_places=2, null=True, blank=True,
                                 help_text='<span style="color:red">如不写，保存时会自动计算</span>')
    updated_at = models.DateField('修改时间', auto_now=True)
    remark = models.TextField('备注', max_length=256, null=True, blank=True)
    is_valid = models.BooleanField('审核', default=False)

    class Meta:
        db_table = 'order_list'
        verbose_name = '开单/退款'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return '订单流水号：' + self.sn

    def remark_min(self):
        """ 备注过长时显示缩略 """
        if len(str(self.remark)) > 21:
            return '{}...'.format(str(self.remark)[0:21])
        else:
            return str(self.remark)

    remark_min.short_description = '备注'

    def clean(self):
        super().clean()
        if self.is_valid is True:
            raise ValidationError('已审核的无法修改')

        if self.receipt is None and self.pay is None and self.types == 10:
            self.receipt = abs(self.recharge) / (1 + self.client_rebate / 100)
            self.pay = abs(self.recharge) / (1 + self.media_rebate / 100)

        elif self.receipt is None and self.pay is None and self.types == 20:
            self.receipt = abs(self.recharge) / (1 + self.media_rebate / 100)
            self.pay = abs(self.recharge) / (1 + self.client_rebate / 100)

        try:
            if self.profit is None:
                self.profit = self.receipt - self.pay
        except TypeError:
            raise ValidationError('收款和打款不能空一个，要么都填，要么都不填')


class Report(OrderRefund):
    """ 报表 """

    def date_format(self):
        """ 日期格式化 """
        if self.types == 10:
            color_code = 'black'
            result = self.created_at.strftime('%Y-%m-%d')
        else:
            color_code = 'red'
            result = self.created_at.strftime('%Y-%m-%d')
        return format_html(
            '<span style="color:{0};">{1}</span>',
            color_code,
            result,
        )

    def sales_color(self):
        """ 销售的颜色设定 """
        if self.types == 10:
            color_code = 'black'
            result = self.sales
        else:
            color_code = 'red'
            result = self.sales
        return format_html(
            '<span style="color:{0};">{1}</span>',
            color_code,
            result,
        )

    def operation_color(self):
        """ 运营的颜色设定 """
        if self.types == 10:
            color_code = 'black'
            result = self.operation
        else:
            color_code = 'red'
            result = self.operation
        return format_html(
            '<span style="color:{0};">{1}</span>',
            color_code,
            result,
        )

    def recharge_color(self):
        """ 账户币的颜色设定 """
        if self.types == 10:
            color_code = 'black'
            result = self.recharge
        else:
            color_code = 'red'
            result = self.recharge
        return format_html(
            '<span style="color:{0};">{1}</span>',
            color_code,
            result,
        )

    def media_rebate_color(self):
        """ 媒体返点的颜色设定 """
        if self.types == 10:
            color_code = 'black'
            result = self.media_rebate
        else:
            color_code = 'red'
            result = self.media_rebate
        return format_html(
            '<span style="color:{0};">{1}</span>',
            color_code,
            result,
        )

    def client_rebate_color(self):
        """ 客户返点的颜色设定 """
        if self.types == 10:
            color_code = 'black'
            result = self.client_rebate
        else:
            color_code = 'red'
            result = self.client_rebate
        return format_html(
            '<span style="color:{0};">{1}</span>',
            color_code,
            result,
        )

    def receipt_color(self):
        """ 收款的颜色设定 """
        if self.types == 10:
            color_code = 'black'
            result = self.receipt
        else:
            color_code = 'red'
            result = self.receipt
        return format_html(
            '<span style="color:{0};">{1}</span>',
            color_code,
            result,
        )

    def pay_color(self):
        """ 打款的颜色设定 """
        if self.types == 10:
            color_code = 'black'
            result = self.pay
        else:
            color_code = 'red'
            result = self.pay
        return format_html(
            '<span style="color:{0};">{1}</span>',
            color_code,
            result,
        )

    def profit_color(self):
        """ 自定义毛利字段颜色 """
        if self.types == 10:
            color_code = 'black'
            result = self.profit
        else:
            color_code = 'red'
            result = self.profit
        return format_html(
            '<span style="color:{0};">{1}</span>',
            color_code,
            result,
        )

    profit_color.short_description = '毛利'
    date_format.short_description = '创建日期'
    sales_color.short_description = '销售'
    operation_color.short_description = '运营'
    recharge_color.short_description = '账户币'
    media_rebate_color.short_description = '媒体返点'
    client_rebate_color.short_description = '客户返点'
    receipt_color.short_description = '收款'
    pay_color.short_description = '打款'

    # 指定排序依据
    profit_color.admin_order_field = 'profit'
    date_format.admin_order_field = 'created_at'
    sales_color.admin_order_field = 'sales'
    operation_color.admin_order_field = 'operation'
    recharge_color.admin_order_field = 'recharge'
    receipt_color.admin_order_field = 'receipt'
    pay_color.admin_order_field = 'pay'

    class Meta:
        verbose_name = '报表与审核'
        verbose_name_plural = verbose_name
        proxy = True
